
/*
 *   Copyright [Xin Li] schindlerlee@gmail.com
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

#ifndef TM_h
#define TM_h

#include <pthread.h>
#include <cassert>
#include <queue>
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
using namespace std;

typedef unsigned int uint;
namespace TM {

	class Job 
		/* The base class of the job for Thread Manager
		 * the run function needed to be overloaded
		 * */
	{
		public:
			Job();
			virtual void run();
	};

	class Mutex
	{
		private:
			pthread_mutex_t this_lock;
		public:
			Mutex();
			~Mutex(); 
			void lock(); 
			void unlock();
	};

	class ThreadManager
		/*
		 * create thread_num threads, append Job class's descent to the queue
		 * the thread will fetch job and run.
		 * */
	{
		private:
			Mutex mutex0, mutex1, mutex2;
			bool running;
			uint thread_num;
			uint running_jobs;
			queue<Job *> jobs;
			pthread_t *threads; 

		public: 
			ThreadManager (uint size);
			~ThreadManager (); 

			uint size();        /* the job size in Thread Manager      */
			void append(Job *); /* append a job to the queue          */
			void sync();        /* wait till all the jobs are done    */
			void worker();      /* the slave process to fetch and run */
	};

}
#endif //TM_h
